<?php

namespace Futures\Controller;
use Think\Controller;

/**
 * 前台公共控制器
 * 为防止多分组Controller名称冲突，公共Controller名称统一使用分组名称
 */
class BaseController extends Controller {

	protected $appid;		//公众号id
	protected $secret;	//公众号密匙
	protected $token;		//公众号token
	protected $public_config;	//公众号配置信息
	/**
	 * [_empty 空操作，用于输出404页面]
	 * @return [type] [description]
	 */
	public function _empty(){
		$this->redirect('Index/index');
	}
	
	/**
	 * [init_public 初始化公招信息]
	 * @return [type] [description]
	 */
	protected function init_public(){
		//约定该系统所使用的公众号始终是uid为1的(admin)账号的当前使用的公众号信息
		//获取公众号id
		$where = array();
		$where['uid'] = 1;
		$where['is_use'] = 1;
		$where['is_creator'] =1;
		$mp_id = M('MemberPublicLink')->where($where)->getField('mp_id');
		//获取公众号信息
		$public = M('MemberPublic')->field('token,appid,secret,addon_config')->find($mp_id);
		//初始化赋值
		$this->appid = $public['appid'];
		$this->secret = $public['secret'];
		$this->token = $public['token'];

		$config = json_decode($public['addon_config'],true);
		$config = $config['Leaflets'];
		$config ['img'] = is_numeric ( $config ['img'] ) ? get_cover_url ( $config ['img'] ) :'';
		$this->public_config = $config;
		$this->assign('public_config',$this->public_config);
	}
	
	/**
	 * [_initialize 任何控制器之前的初始化操作，主要用于微信登录]
	 * @return [type] [description]
	 */
	function _initialize() {
		$this->init_public();
		//获取shareuserid
		$shareuserid = I('get.shareuserid');
		$shareuserid = base64_decode($shareuserid);
		if($shareuserid){
			cookie('shareuserid',$shareuserid);
		}
		if(ACTION_NAME=='pwd_login' || ACTION_NAME=='notify' || ACTION_NAME=='attention_weixin' || ACTION_NAME=='register' || ACTION_NAME=='send_verify' || ACTION_NAME=='user_register_add') return;

		$user = cookie('user_auth');
		$openid = $user['openid'];


		// $user=array('uid'=>412,'openid'=>'o6VUpxI3SRM2vaw9FJIMUmxjO2to');
		// cookie('user_auth',$user);
		$res = M ( 'Follow' )->field('id,nickname,headimgurl,login_time,subscribe,is_futures_user,route,mobile,is_agent')->where(array('openid'=>$openid,'status'=>1))->find();
		//判断用户openid是否存在
		if(!$user['openid'] || empty($user['uid']) || empty($res)){
			//如果不存在则重新获取openid并且保存进session
			$state=str_replace("&","△",$_SERVER['REQUEST_URI']);
			$redirect_uri="http://" . $_SERVER['HTTP_HOST'] ."/futures.php?s=/Base/weixin_call_back";
			$appid = $this->appid;
			$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".urlencode($redirect_uri)."&response_type=code&scope=snsapi_base&state=".$state."#wechat_redirect";
			header("location:".$url."");
		}else{

				  
	        $headimgurl = $res['headimgurl'];
	        //dump($res);
	        $this->assign('headimgurl',$headimgurl);
	        

	        $url=get_url();
	        $pos = strpos($url,'?');
	        if(false===$pos){
				$share_url = $url.'?s=/Index/index/shareuserid/'.base64_encode($user['uid']);
	        }else{
	        	$p = strpos($url,'shareuserid');
	        	if(false===$p){
	        		$share_url = $url.'/shareuserid/'.base64_encode($user['uid']);
	        	}else{
	        		$share_url = mb_substr($url,0,$p).'shareuserid/'.base64_encode($user['uid']);;
	        	}
	        }
			
			$this->assign('share_url',$share_url);

	        $info = $this->getWeixinUserInfo($openid);
	        //if(isset($info['errcode'])) cookie('user_auth',null);
			//dump($openid);dump($info);exit;
			if(!$res['is_futures_user'] || $info['nickname']!=$res['nickname']){
				$shareuserid = cookie('shareuserid');
				//dump($shareuserid);
				if($shareuserid && empty($res['route'])){
					$pinfo = M('Follow')->field('id,route')->where('id='.$shareuserid)->find();
					if($pinfo['id']){
						$p_route = $pinfo['route']; 
						$route = $p_route.','.$shareuserid;
						$route = trim($route,',');
						//判断是否包含本身
						$routes = explode(',',$route);
						if(!in_array($user['uid'], $routes)){
							$info['route'] = $route;
							$info['maker_id'] = $pinfo['maker_id'];
							if($info['maker_id']<=1){
								$info['maker_id'] = 1;
							}
						}
					}
					
				}
				$info['is_futures_user'] = 1;
				//dump($userinfo);
				D ( 'Common/Follow' )->where ( array('openid'=>$openid) )->save ( $info );
			}
			
			if(CONTROLLER_NAME=='Coupon'){	//如果是代金券模块不进行登录限制
				$this->assign('hasPwd','none');
				return;
			}
			//判断后移
			if($res['subscribe']!=1){
				if(!$info['subscribe']){
					//跳转到关注页面
					$subscribeurl = U('Public/attention_weixin');
					redirect($subscribeurl);
					exit;
				}else{
					D ( 'Common/Follow' )->where (array('openid'=>$openid,'status'=>1) )->save ( $info );
				}
				
			}
			//判断是否有注册
			if(empty($res['mobile'])){
				$subscribeurl = U('User/register');
				redirect($subscribeurl);
				exit;
			}
			//判断是否输入交易密码
			$f_pwd = session($user['uid'].'_futures_pwd');
			$this->assign('hasPwd','none');
			if(empty($f_pwd)){
			 	$this->assign('hasPwd','block');
			}else{
			 	$this->assign('hasPwd','none');
			}

			$this->assign('is_agent',$res['is_agent']);
		}
		
	}

	/**
	 * [weixin 授权登录回调函数]
	 * @return [type] [description]
	 */
	public function weixin_call_back(){
		//获取回调参数
		$code=$_GET['code'];
		$state=$_GET['state'];
		if($code){
			//APPID 和 APPSERET 替换成为变量 TODO
			$appid = $this->appid;
			$appsecret = $this->secret;
			$back_openid_arr=$this->get_openid($appid,$appsecret,$code);
			$openid = $back_openid_arr['openid'];
			$user['openid'] = $openid;
			
			$userinfo = M ( 'Follow' )->field('id,nickname,openid,status,subscribe_time,login_time')->where(array('openid'=>$openid))->find();
			if(!empty($openid) && !$userinfo){
				$userinfo['token'] = $this->token;
				$shareuserid = cookie('shareuserid');
				if($shareuserid){
					$pinfo = M('Follow')->field('id,route')->where('id='.$shareuserid)->find();
					if($pinfo['id']){
						$p_route = $pinfo['route']; 
						$route = $p_route.','.$shareuserid;
						$route = trim($route,',');
						//判断是否包含本身
						$routes = explode(',',$route);
						if(!in_array($pinfo['id'], $routes)){
							$userinfo['route'] = $route;
							$userinfo['maker_id'] = $pinfo['maker_id'];
							if($info['maker_id']<=1){
								$info['maker_id'] = 1;
							}
						}
					}
					
				}
				//获取分享人id
				/*
				$shareuserid = cookie('shareuserid');
				$p_route = M('Follow')->where('id='.$shareuserid)->getField('route');
				$route = $p_route.','.$shareuserid;
				$route = trim($route,',');
				$userinfo['route'] = $route;
				*/
				$userinfo['login_time'] = time();
				$info = D ( 'Common/Follow' )->init_follow ( $openid,$userinfo);
			}else{
				$user['uid'] = $userinfo['id'];
				$user['nickname'] = $userinfo['nickname'];
				if(empty($userinfo['nickname']) || (time()>$userinfo['login_time']+86400)){ //没有写入详细信息 或者更新时间超过24小时
					$info = $this->getWeixinUserInfo($openid);
					$info['login_time'] = time();
                    $res = D ( 'Common/Follow' )->where ( array('openid'=>$openid) )->save ( $info );
				}         
			}
			
			cookie('user_auth',$user);
			header("location:http://".$_SERVER['HTTP_HOST'].str_replace("△","&",$state));
		}else{
			echo "未授权";
			exit;
		}
	}

	/**
	 * [get_openid description]
	 * @param  [type] $appid     [公众号ID]
	 * @param  [type] $appsecret [公众号密匙]
	 * @param  [type] $code      [回调GET参数]
	 * @return [type]            [openid]
	 */
	function get_openid($appid,$appsecret,$code){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code");
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$tmpInfo = curl_exec($ch);
		if(curl_errno($ch)){
			return curl_error($ch);
		}
		curl_close($ch);
		return json_decode($tmpInfo,true);

	}

	/**
	 * [getWeixinUserInfo 通过openid获取微信用户基本信息,此功能只有认证的服务号才能用]
	 * @param  [type] $openid [description]
	 * @return [type]         [description]
	 */
	function getWeixinUserInfo($openid) {
		if (empty ( $GLOBALS ['user'] ['appid'] )) {
			//return false;
		}
		$appid = $this->appid;
		$appsecret = $this->secret;
		$param ['appid'] = $appid;
		$param ['secret'] = $appsecret;
		$param ['grant_type'] = 'client_credential';
		//token改为缓存获取 TODO
		// $url = 'https://api.weixin.qq.com/cgi-bin/token?' . http_build_query ( $param );
		// $content = file_get_contents ( $url );
		// $content = json_decode ( $content, true );
		// $param2 ['access_token'] = $content['access_token'];
		$param2 ['access_token'] = getAccessToken();
		$param2 ['openid'] = $openid;
		$param2 ['lang'] = 'zh_CN';
		
		$url = 'https://api.weixin.qq.com/cgi-bin/user/info?' . http_build_query ( $param2 );
		$content = file_get_contents ( $url );
		$content = json_decode ( $content, true );
		return $content;
	}

	public function getAccessToken(){
        $file = './Data/token.json';
        if(!file_exists($file) || (file_exists($file) && (time()-filemtime($file))>60)){
            $code=$_GET['code'];
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->secret; 
            $tmpInfo=$this->httpGet($url);
            $info=json_decode($tmpInfo,true);
            $result['access_token']=$info['access_token'];
            file_put_contents($file,json_encode($result));
        }
        $data=file_get_contents($file);
        $data= json_decode($data,true);
        return $data['access_token'];
    }

	protected function httpGet($url, $data = null){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if(curl_errno($ch)){
            return curl_error($ch);
        }
        curl_close($ch);
        return $tmpInfo;
    }

    /**
     * [get_url 获取当前完整的url]
     * @return [string] [当前路径]
     */
    function get_url() {
    	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    	$php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    	$path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    	$relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
    	return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
 }
}
